import datetime
import hashlib
import re
import time

from app.util import yesterday_start_time, yesterday_end_time
from . import user_blu
from flask import render_template, request, session, jsonify, redirect, url_for, current_app
from app import sql
from app.models.model import User, Category, News, Comment, Collection, Follow
from werkzeug.security import generate_password_hash, check_password_hash


@user_blu.route("/index")
def index():
    user = session.get("user_email")
    if user:
        a = sql.session.query(User).filter(User.email == user).first()
        if a:
            a.T_F_sign = 1
            if a.sign_in_time == 0 or yesterday_start_time <= a.sign_in_time <= yesterday_end_time:
                a.T_F_sign = 0
            return render_template("user/index.html", user=a)
    return redirect(url_for("uitl_blu.user_log"))


@user_blu.route("/edit", methods=["GET", "POST"])
def edit():
    categr = request.form.get("type")
    title = request.form.get("title")
    content = request.form.get("content")
    reward = request.form.get("reward")
    img_code = request.form.get("img_code")
    print(categr, title, content, reward, img_code)
    if not all([categr, title, content, reward, img_code]):
        ret = {

        }
    return "fewaf"


# 激活邮箱
@user_blu.route("/activate", methods=["POST", "GET"])
def activate():
    if session.get("user_email"):
        a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        if a:
            return render_template("user/activate.html", user=a)
    elif request.method == "POST":
        vercode = request.form.get("vercode")
        email = request.form.get("email")
        pwd = request.form.get("pass")
        if session.get("vercode").lower() != vercode.lower():
            ret = {"status": 5006, "msg": "验证码错误"}
            return jsonify(ret)
        a = sql.session.query(User).filter(User.email == email).first()
        if not a:
            ret = {"status": 5007, "msg": "该邮箱为被注册"}
            return jsonify(ret)
        if not check_password_hash(a.password_hash, pwd):
            ret = {"status": 5003, "msg": "密码错误"}
            return jsonify(ret)
        if a.activate == "0":
            ret = {"status": 5010, "msg": "该邮箱已激活"}
            return jsonify(ret)
        if a.activate != request.args.get("token"):
            ret = {"status": 5008, "msg": "请到注册的邮箱内使用链接进行激活"}
            return jsonify(ret)
        session["user_email"] = a.email
        session["user_name"] = a.nick_name
        a.activate = "0"
        sql.session.commit()
        ret = {"status": 0, "msg": "激活成功"}
        return jsonify(ret)
    return render_template("user/login.html", a=1)


# 设置
@user_blu.route("/set", methods=["GET", "POST"])
def set():
    user = session.get("user_name")
    a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    if user:
        if request.method == "GET":
            print(user, a)
            return render_template("user/set.html", user=a)
        elif request.method == "POST":
            print(request.json)
            email = request.json.get("email")
            user_name = request.json.get("username")
            sex = request.json.get("gender")
            sign = request.json.get("sign")
            print(email, user_name, sex, sign)
            if all([email, user_name, sex]):
                if email == session.get("user_email"):
                    if 3 <= len(user_name) <= 10 or not user_name.isalnum():
                        b = sql.session.query(User).filter(User.nick_name == user_name, User.email != email).first()
                        if not b:
                            a.nick_name = user_name
                            a.gender = sex
                            a.signature = sign
                            sql.session.commit()
                            ret = {"status": 0, "msg": "修改成功"}
                            return jsonify(ret)
                        ret = {"status": 8004, "msg": "该用户名已被使用，请重新修改"}
                        return jsonify(ret)
                    ret = {"status": 8003, "msg": "用户名不符合规范，用户名只能3到10位并且只能是数字和字母"}
                    return jsonify(ret)
                ret = {"status": 8002, "msg": "邮箱错误，邮箱不能被修改"}
                return jsonify(ret)
            ret = {"status": 8001, "msg": "缺少数据"}
            return jsonify(ret)
    return redirect(url_for("uitl_blu.user_log"))


# 我的主页
@user_blu.route("/home", methods=["GET", "POST"])
def home():
    user = session.get("user_name")
    u_id = request.args.get("u")
    num = request.args.get("page")
    try:
        num = int(num)
    except:
        num = 1
    answer = sql.session.query(Comment).filter(Comment.user_id == u_id).order_by(Comment.create_time.desc()).paginate(
        1, 3, False)
    news = sql.session.query(News).filter(News.user_id == u_id).order_by(News.create_time.desc()).paginate(num, 10,
                                                                                                           False)
    if num > answer.pages:
        num1 = answer.pages
        answer = sql.session.query(Comment).filter(Comment.user_id == u_id).order_by(
            Comment.create_time.desc()).paginate(
            num1, 3, False)
    elif num > news.pages:
        num1 = news.pages
        news = sql.session.query(News).filter(News.user_id == u_id).order_by(News.create_time.desc()).paginate(num1,10,False)

    if user:
        a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        if request.method == "GET":
            create_time = str(a.create_time)
            a.create_time = create_time[:10]
            other = sql.session.query(User).filter(User.id == u_id).first()
            create_times = str(other.create_time)
            other.create_time = create_times[:10]
            a.other = other
            other.gz = len(other.followed.all())
            other.fs = len(other.followers.all())
            if a:
                return render_template("user/home.html", user=a, news=news, answer=answer)
            return redirect(url_for("uitl_blu.user_log"))
        elif request.method == "POST":
            print(request.json)
            follow_id = request.json.get("follow")
            zl = request.json.get("zl")
            b = sql.session.query(Follow).filter(Follow.follower_id == a.id, Follow.followed_id == follow_id).first()
            if zl == "do":
                if not all([zl, follow_id]):
                    ret = {"errno": "9003", "msg": "缺少数据，关注失败"}
                    return jsonify(ret)
                if follow_id == a.id:
                    ret = {"errno": "9003", "msg": "不能关注自己"}
                    return jsonify(ret)
                if b:
                    ret = {"errno": "0", "msg": "已关注"}
                    return jsonify(ret)
                foll = Follow()
                foll.followed_id = follow_id
                foll.follower_id = a.id
                sql.session.add(foll)
                sql.session.commit()
                ret = {"errno": "0", "msg": "关注成功"}
                return jsonify(ret)
            elif zl == "undo":
                if not all([zl, follow_id]):
                    ret = {"errno": "9003", "msg": "缺少数据，关注失败"}
                    return jsonify(ret)
                sql.session.delete(b)
                sql.session.commit()
                ret = {"errno": "0", "msg": "取消关注成功"}
                return jsonify(ret)
            ret = {"errno": "9003", "msg": "数据错误"}
            return jsonify(ret)

    elif request.method == "GET":
        a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        other = sql.session.query(User).filter(User.id == u_id).first()
        if not a:
            a = news
        create_times = str(other.create_time)
        other.create_time = create_times[:10]
        a.other = other
        other.gz = len(other.followed.all())
        other.fs = len(other.followers.all())
        create_time = str(news.items[0].user.create_time)
        a.create_time = create_time[:10]
        return render_template("user/home.html", user=a, news=news, answer=answer)
    else:
        ret = {"errno": "3002", "msg": "请先登录"}
        return jsonify(ret)

# 我的收藏
@user_blu.route("/collect", methods=["POST", "GET"])
def collect():
    user = session.get("user_name")
    num = request.args.get("page")
    if not num:
        num = 1
    else:
        try:
            num = int(num)
        except:
            num = 1
    if user:
        a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        if request.method == "GET":
            news = sql.session.query(Collection).filter(Collection.user_id == a.id).order_by(Collection.create_time.desc()).paginate(num, 10,False)
            return render_template("user/collect.html", user=a, news=news)
        elif request.method == "POST":
            zl = request.json.get("zl")
            news = sql.session.query(Collection).filter(Collection.user_id == a.id, Collection.news_id == request.json.get("news_id")).first()
            if not news and zl == "do":
                coll = Collection()
                coll.news_id = request.json.get("news_id")
                coll.user_id = a.id
                sql.session.add(coll)
                sql.session.commit()
                ret = {"errno": "0", "msg": "收藏成功"}
            elif news and zl == "undo":
                sql.session.delete(news)
                sql.session.commit()
                ret = {"errno": "0", "msg": "取消收藏成功"}
            else:
                ret = {"errno": "9002", "msg": "数据错误，操作失败"}
            return jsonify(ret)
    return redirect(url_for("uitl_blu.user_log"))

# 我的帖子
@user_blu.route("/user_message")
def user_message():
    user = session.get("user_name")
    num = request.args.get("page")
    if not num:
        num = 1
    else:
        try:
            num = int(num)
        except:
            num = 1
    if user:
        a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        news = sql.session.query(News).filter(News.user_id == a.id).order_by(News.create_time.desc()).paginate(num, 10,False)
        a.news_content = len(a.news)

        return render_template("user/content.html", user=a, news=news)
    return redirect(url_for("uitl_blu.user_log"))

# 我的关注
@user_blu.route("/follow", methods=["GET", "POST"])
def follow():
    user = session.get("user_name")
    num = request.args.get("page", 1)
    try:
        num = int(num)
    except:
        num = 1
    if user:
        a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        if request.method == "GET":
            news = sql.session.query(Follow).filter(Follow.follower_id == a.id).paginate(num, 4, False)
            follow_list = []
            for i in news.items:
                b = sql.session.query(User).filter(User.id == i.followed_id).first()
                follow_list.append(b)
            return render_template("user/follow.html", user=a, follow=follow_list, page=news)
        do_id = request.json.get("follow_id")
        follow_do = sql.session.query(Follow).filter(Follow.follower_id == a.id, Follow.followed_id == do_id).first()
        try:
            sql.session.delete(follow_do)
            sql.session.commit()
            ret = {"errno": 0, "msg": "取消关注成功"}
            return jsonify(ret)
        except:
            ret = {"errno": 9001, "msg": "请求错误"}
            return jsonify(ret)

    return redirect(url_for("uitl_blu.user_log"))


# 修改密码
@user_blu.route("/repass", methods=["GET", "POST"])
def repass():
    if request.method == "POST" and session.get("user_email"):
        if request.json.get("old_pwd"):
            old_pwd = request.json.get("old_pwd")
            pwd1 = request.json.get("pwd1")
            pwd2 = request.json.get("pwd2")
            if all([old_pwd, pwd2, pwd1]):
                if pwd1 != pwd2:
                    ret = {"status": 7009, "msg": "两个新密码不一样，请重新修改"}
                    return jsonify(ret)
                if 6 > len(pwd1) > 20:
                    ret = {"status": 7010, "msg": "新密码长度不符合规范, 密码长度只能在6到20位之间"}
                    return jsonify(ret)
                a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
                if not check_password_hash(a.password_hash, old_pwd):
                    ret = {"status": 7003, "msg": "原密码错误，请输入正确的原密码"}
                    return jsonify(ret)
                a.password_hash = pwd1
                sql.session.commit()
                ret = {"status": 0, "msg": "修改成功"}
                return jsonify(ret)
            ret = {"status": 7001, "msg": "缺少数据"}
            return jsonify(ret)
        ret = {"status": 7002, "msg": "请求错误"}
        return jsonify(ret)
    return redirect(url_for("uitl.user_log"))


# 上传头像
@user_blu.route("/upload/", methods=["POST"])
def upload():
    if not session.get("user_email"):
        return redirect(url_for("uitl.user_log"))
    file = request.files.get("file")
    if file:
        print(current_app.root_path)
        file_name = file.filename
        gx = file_name[file_name.rfind("."):]
        hash_name = hashlib.md5()
        hash_name.update((str(time.time()) + file_name).encode("utf-8"))
        file_name = hash_name.hexdigest()
        file.save(current_app.root_path + "/static/images/user_avatar/" + file_name + gx)
        user = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        print(user)
        user.avatar_url = "/static/images/user_avatar/" + file_name + gx
        sql.session.commit()
        ret = {"status": 0, "msg": "修改成功"}
        return jsonify(ret)

    ret = {"status": 5002, "msg": "修改失败"}
    return jsonify(ret)


# 由于js的原因， 当修改完头像后会跳转到 /user/set/. 多了一个反斜杠， 所以， 在蓝图中添加一个跳转
@user_blu.route("/set/", methods=["POST"])
def sets():
    return redirect(url_for(".set"))


# 发表帖子
@user_blu.route("/add", methods=["GET", "POST"])
def add():
    if request.method == "GET":
        return render_template("jie/add.html")
    elif request.method == "POST":
        user = sql.session.query(User).filter(User.email == session.get("user_email")).first()
        if not user:
            ret = {"errno": "8009", "msg": "请先登录"}
            return jsonify(ret)
        if user.activate != 0:
            ret = {"errno": "9006", "msg": "请先激活邮箱"}
            return jsonify(ret)
        tie_type = request.json.get("type")
        title = request.json.get("title")
        content = request.json.get("content")
        reward = request.json.get("reward")
        img_code = request.json.get("img_code")
        if not all([tie_type, title, content, reward, img_code]):
            ret = {"errno": "8004", "msg": "缺少数据"}
            return jsonify(ret)
        if session.get("vercode").lower() != img_code.lower():
            ret = {"errno": 4005, "msg": "验证码错误"}
            return jsonify(ret)
        news = News()
        news.content = content
        news.user_id = user.id
        news.title = title
        news.award = reward
        news.category_id = tie_type
        sql.session.add(news)
        sql.session.commit()
        ret = {"errno": "0", "msg": "发表成功"}
        return jsonify(ret)
    return redirect(url_for("index_blu.index"))


# 退出
@user_blu.route("/logout")
def logout():
    a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    # 获取当前时间， 当前dt是一个字符串
    dt = datetime.datetime.now().strftime("%Y-%m-%d%H:%M:%S")
    # 将dt字符串转换为 datetime.datetime类型的数据
    date_time = datetime.datetime.strptime(dt, '%Y-%m-%d%H:%M:%S')
    # 将这个数据添加到数据库中
    a.last_login = date_time
    sql.session.commit()
    session.clear()
    return redirect(url_for("index_blu.index"))


# 回复
@user_blu.route("/reply", methods=["GET", "POST"])
def reply():
    if not session.get("user_email"):
        ret = {"errno": "8009", "msg": "请先登录"}
        return jsonify(ret)
    content = request.json.get("content")
    reply_id = request.json.get("reply_id")
    news_id = request.json.get("news_id")
    if not all([content, reply_id, news_id]):
        ret = {"errno": "9008", "msg": "缺少数据，评论失败"}
        return jsonify(ret)
    a = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    if a.activate != "0":
        ret = {"errno": "9006", "msg": "请先激活邮箱"}
        return jsonify(ret)
    comment = Comment()
    comment.news_id = news_id
    comment.content = content
    comment.user_id = a.id
    if reply_id != "None":
        comment.comment_user = reply_id
    sql.session.add(comment)
    sql.session.commit()
    ret = {"errno": "0", "msg": "评论成功"}
    return jsonify(ret)


# 飞吻商城
@user_blu.route("/fly_kiss")
def fly_kiss():
    user = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    if user:
        return render_template("user/fly_kiss.html", user=user)
    return redirect(url_for("uitl.user_log"))


@user_blu.route("/pay")
def pay():
    user = sql.session.query(User).filter(User.email == session.get("user_email")).first()
    if user:
        return render_template("user/pay.html", user=user)
    return redirect(url_for("uitl.user_log"))
